const User = require("../Models/user");
const Question = require("../Models/question");
const encryption = require("../Models/encryption");
const mongoose = require('mongoose');
const https = require('https');

exports.login = async ctx => {
    // 用户登录 post 发过来的数据
    const user = ctx.request.body;
    if (user.code) {
        let appid = 'wx116f2c611ddfcf36';
        let secret = '3531ae98d547ffb3ac41295b6e72e447';
        let js_code = user.code;
        let grant_type = 'authorization_code';
        let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=${grant_type}`;
        await new Promise((resolve) => {
            https.get(url, res => {
                res.on('data', data => {
                    let result = JSON.parse(data);
                    resolve(result)
                });
                //res.on("end", () => {});
            }).on("error", err => {
                console.log(err)
            });
        })
            .then(result => {
                ctx.body = result;
            })
    }else {
        const username = user.username;
        const password = encryption(user.password);
        //去数据库 user 查询 username 是否存在
        await new Promise((resolve, reject) => {
            User.find({username}, (err, data) => {
                // 判断查找是否出错
                if (err) return reject(err);

                // 判断返回数据是否为空，空则用户不存在
                if (data.length !== 0) {
                    //console.log(data)
                    resolve(data);
                } else {
                    resolve(false);
                }
            })
        })
            .then(data => {
                if (data) {
                    if (JSON.parse(JSON.stringify(data[0])).password === password) {
                        ctx.cookies.set("username", username, {
                            domain: 'localhost',
                            path: '/',
                            maxAge: 10000,
                            httpOnly: true,
                            overwrite: false
                        });
                        ctx.body = {
                            status: 200,
                            msg: "登录成功"
                        }
                    } else {
                        ctx.body = {
                            status: 404,
                            msg: "密码错误"
                        }
                    }
                } else {
                    ctx.body = {
                        status: 404,
                        msg: "用户不存在"
                    }
                }
            })
            .catch(err => {
        console.log(err);
        ctx.body = {
            status: 404,
            msg: "未知错误"
        }
    })
    }
};

// 确定用户的状态  保持用户的状态
exports.keepLog = async (ctx, next) => {
    console.log(ctx.session.isNew)
    if (ctx.session.isNew) {// session没有
        if (ctx.cookies.get("username")) {
            ctx.session = {
                username: ctx.cookies.get('username')
            }
        }
    }
    await next()
};

// 用户获取试题
exports.quesList = async ctx => {
    const data = ctx.request.query;
    await Question
        .find(data)
        .then(data => {
            //console.log(data)
            ctx.body = {
                status: 200,
                data
            }
        })
        .catch(err => {

        })
};

// 用户试题结果
exports.quesAns = async ctx => {
    const data = ctx.request.body;
    const username = data.username;
    const ans = data.ans;
    const quesName = data.quesName;
    let [F1, F2, F3, F4, F5, F6, F7, F8, F9, F10] = new Array(10).fill(0);
    let f1Reg = /ans01|ans04|ans12|ans27|ans40|ans42|ans48|ans49|ans52|ans53|ans56|ans58/; // 躯体化12
    let f2Reg = /ans03|ans09|ans10|ans28|ans38|ans45|ans46|ans51|ans55|ans65/; // 强迫10
    let f3Reg = /ans06|ans21|ans34|ans36|ans37|ans41|ans61|ans69|ans73/; // 人际关系9
    let f4Reg = /ans05|ans14|ans15|ans20|ans22|ans26|ans29|ans30|ans31|ans32|ans54|ans71|ans79/; // 抑郁13
    let f5Reg = /ans02|ans17|ans23|ans33|ans39|ans57|ans72|ans78|ans80|ans86/; // 焦虑10
    let f6Reg = /ans11|ans24|ans63|ans67|ans74|ans81/; // 敌对性6
    let f7Reg = /ans13|ans25|ans47|ans50|ans70|ans75|ans82/; // 恐惧7
    let f8Reg = /ans08|ans18|ans43|ans68|ans76|ans83/; // 偏执6
    let f9Reg = /ans07|ans16|ans35|ans62|ans77|ans84|ans85|ans87|ans88|ans90/; // 精神病性10
    let f10Reg = /ans19|ans44|ans59|ans60|ans64|ans66|ans89/; // 睡眠、饮食及其他7
    let fnReg = [f1Reg, f2Reg, f3Reg, f4Reg, f5Reg, f6Reg, f7Reg, f8Reg, f9Reg, f10Reg];
    // 因子得分
    for (let item in ans) {
        let value = Number(ans[item]);
        if (f1Reg.test(item)) {
            F1 += value;
        }else if (f2Reg.test(item)) {
            F2 += value;
        }else if (f3Reg.test(item)) {
            F3 += value;
        }else if (f4Reg.test(item)) {
            F4 += value;
        }else if (f5Reg.test(item)) {
            F5 += value;
        }else if (f6Reg.test(item)) {
            F6 += value;
        }else if (f7Reg.test(item)) {
            F7 += value;
        }else if (f8Reg.test(item)) {
            F8 += value;
        }else if (f9Reg.test(item)) {
            F9 += value;
        }else {
            F10 += value;
        }
    }
    // T 分数
    let Fn = [F1, F2, F3, F4, F5, F6, F7, F8, F9, F10];
    function T(reg, Fn) {
        let Tn = [];
        for (let i = 0; i < Fn.length; i++) {
            let length = String(reg[i]).split("|").length;
            let T = "T" + (i + 1);
            let Ts = Fn[i] / length;
            Tn.push({
                [T]: Ts
            })
        }
        return Tn
    }
    let Tn = T(fnReg, Fn);
    // 因子分常模
    let X = [
        {
            x: 1.37,
            sd: 0.48
        },
        {
            x: 1.62,
            sd: 0.58
        },
        {
            x: 1.65,
            sd: 0.61
        },
        {
            x: 1.50,
            sd: 0.59
        },
        {
            x: 1.39,
            sd: 0.43
        },
        {
            x: 1.46,
            sd: 0.55
        },
        {
            x: 1.23,
            sd: 0.41
        },
        {
            x: 1.43,
            sd: 0.57
        },
        {
            x: 1.29,
            sd: 0.42
        },
        {
            x: 1.45,
            sd: 0.44
        }
    ];
    ctx.body = {
        status: 200,
        X,
        Tn,
    };

    let sum = F1 + F2 + F3 + F4 + F5 + F6 + F7 + F8 + F9 + F10;
    User.find({username})
        .then(res => {
            let data = res[0];
            let _id = data._id;
            let resData = JSON.parse(JSON.stringify(data));
            resData.test.push({
                quesName,
                sum,
                Tn,
                X,
                ans
            });
            resData._id = mongoose.Types.ObjectId(_id);
            User.collection.update({_id}, resData)
                .then(res => {
                    console.log("保存成功")
                })
        })


};

// 试题记录
exports.history = async ctx => {
    const username = ctx.request.query.username;
    await User
        .find({username})
        .then(data => {
            let test = JSON.parse(JSON.stringify(data[0])).test;
            console.log('查找成功');
            ctx.body = {
                status: 200,
                test
            }
        })
};

// 情绪分析
exports.analysis = async ctx => {
    const text = ctx.request.query.text;
    const AipOcrClient = require("aip-node-sdk-2.3.8").nlp;

    // 设置APPID/AK/SK
    const APP_ID = "16193125";
    const API_KEY = "WB0848G6MllSDH8KyUqqinu1";
    const SECRET_KEY = "vADzBMIPwOMyAeH8CO3C0rRtLRfrdMa9";

    // 新建一个对象
    const client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);
    await new Promise((resolve, reject) => {
        // 调用词法分析
        let sentimentClassify = client.sentimentClassify(text);

        // 可选参数
        let options = {};
        options["scene"] = "talk";
        // 带参数调用对话情绪识别接口
        let emotion = client.emotion(text, options)

        Promise.all([sentimentClassify, emotion])
            .then(function (result) {
                resolve(result);
            }).catch(function (err) {
            // 如果发生网络错误
            reject(err);
        });
    }).then(res => {
        console.log(res);
        ctx.body = {
            status: 200,
            res
        }
    }).catch(async err => {
        console.log(err);
    })
};